package com.tongtong.stsuserapi.service.base.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tongtong.stscommon.enumration.Message;
import com.tongtong.stscommon.enumration.OrderState;
import com.tongtong.stscommon.enumration.Status;
import com.tongtong.stscommon.exception.STSOrderOperationException;
import com.tongtong.stscommon.exception.STSResourcesOperationException;
import com.tongtong.stscommon.message.STSMessage;
import com.tongtong.stscommon.message.STSSuccessMessage;
import com.tongtong.stscommon.utils.checker.ObjectChecker;
import com.tongtong.stsuserapi.dao.CommentDao;
import com.tongtong.stsuserapi.dao.OrderDao;
import com.tongtong.stsuserapi.dao.UserDao;
import com.tongtong.stsuserapi.pojo.Comment;
import com.tongtong.stsuserapi.pojo.Order;
import com.tongtong.stsuserapi.pojo.User;
import com.tongtong.stsuserapi.service.base.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

	@Autowired
	CommentDao commentDao;

	@Autowired
	UserDao userDao;

	@Autowired
	OrderDao orderDao;

	@Override
	public STSMessage postComment(Long userId, Long orderId, Integer score, String content) {

		Order order = orderDao.selectById(orderId);
		ObjectChecker.ObjectsFromDBNullCheck(order);

		User seller = userDao.selectById(order.getSellerId());
		ObjectChecker.ObjectsFromDBNullCheck(seller);

		// 检查订单是否属于当前用户
		if(!userId.equals(order.getUserId())) {
			throw new STSResourcesOperationException(Status.AccessResourcesError, Message.AccessResourcesError);
		}
		//检查订单是否已经完成
		if(!order.getOrderState().equals(OrderState.COMPLETED)) {
			throw new STSOrderOperationException(Status.OrderStateError,Message.OrderStateError);
		}

		if(score>5) score=5;
		if(score<1) score=1;
		// 创建评论
		Comment comment = new Comment();
		comment.setContent(content);
		comment.setScore(score);
		comment.setBuyerId(userId);
		comment.setSellerId(order.getSellerId());
		comment.setOrderId(orderId);
		comment.setPostTime(new Timestamp(System.currentTimeMillis()));

		try	{
			commentDao.insert(comment);
		} catch (Exception e) {
			throw new STSResourcesOperationException(Status.AddResourcesError,e.getMessage());
		}

		// 更新订单状态
		order.setOrderState(OrderState.REVIEWED);
		try {
			orderDao.updateById(order);
		} catch (Exception e) {
			throw new STSResourcesOperationException(Status.UpdateResourcesError,e.getMessage());
		}

		// 计算用户星级
		LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
		lqw.eq(Comment::getSellerId,order.getSellerId());
		List<Comment> comments = commentDao.selectList(lqw);

		double averageScore = comments.stream()
				.mapToDouble(Comment::getScore)
				.average()
				.orElse(0D);

		// 更新用户状态
		seller.setScore(averageScore);
		try {
			userDao.updateById(seller);
		} catch (Exception e) {
			throw new STSResourcesOperationException(Status.UpdateResourcesError,e.getMessage());
		}

		return STSSuccessMessage.from(Status.OK,Message.OK);
	}

	@Override
	public STSMessage deleteComment(Long userId, Long commentId) {

		Comment comment = commentDao.selectById(commentId);
		ObjectChecker.ObjectsFromDBNullCheck(comment);

		// 检查订单是否属于当前用户
		if(!userId.equals(comment.getBuyerId())) {
			throw new STSResourcesOperationException(Status.AccessResourcesError, Message.AccessResourcesError);
		}

		try	{
			commentDao.deleteById(commentId);
		} catch (Exception e) {
			throw new STSResourcesOperationException(Status.DeleteResourcesError,e.getMessage());
		}

		User seller = userDao.selectById(comment.getSellerId());
		ObjectChecker.ObjectsFromDBNullCheck(seller);

		// 计算用户星级
		LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
		lqw.eq(Comment::getSellerId,seller.getId());
		List<Comment> comments = commentDao.selectList(lqw);

		double averageScore = comments.stream()
				.mapToDouble(Comment::getScore)
				.average()
				.orElse(0D);

		// 更新用户状态
		seller.setScore(averageScore);
		try {
			userDao.updateById(seller);
		} catch (Exception e) {
			throw new STSResourcesOperationException(Status.UpdateResourcesError,e.getMessage());
		}
		return STSSuccessMessage.from(Status.OK,Message.OK);
	}

	@Override
	public STSMessage getCommentsAndScore(Long userId) {

		LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper<>();
		lqw.eq(Comment::getSellerId,userId);
		List<Comment> list = commentDao.selectList(lqw);

		User seller = userDao.selectById(userId);
		ObjectChecker.ObjectsFromDBNullCheck(seller);


		HashMap<String,Object> map = new HashMap<>();
		map.put("list",list);
		map.put("score",seller.getScore());

		return STSSuccessMessage.from(map);
	}
}
